#!/usr/bin/perl -w
# This code cannot be redistributed without permissions.
#
# mt-sql2db.cgi: copying data from your SQL database to BerkeleyDB

use strict;
local $| = 1;

my($MT_DIR);
BEGIN {
    if ($0 =~ m!(.*[/\\])!) {
        $MT_DIR = $1;
    } else {
        $MT_DIR = './';
    }
    unshift @INC, $MT_DIR . 'lib';
    unshift @INC, $MT_DIR . 'extlib';
}

print "Content-Type: text/html\n\n";
print <<HTML;
<html>
<head><title>MT-SQL2DB: Copying data from your SQL database to BerkeleyDB</title></head>
<body>
<h1>MT-SQL2DB: Copying data from your SQL database to BerkeleyDB</h1>

<pre>
HTML

my @CLASSES = qw( MT::Author MT::Blog MT::Category MT::Comment MT::Entry
                  MT::IPBanList MT::Log MT::Notification MT::Permission
                  MT::Placement MT::Template MT::TemplateMap MT::Trackback
                  MT::TBPing );

eval {
    local $SIG{__WARN__} = sub { print "**** WARNING: $_[0]\n" };

    require MT;
    my $mt = MT->new( Config => $MT_DIR . 'mt.cfg', Directory => $MT_DIR )
        or die MT->errstr;

    require MT::Object;
    my ($type) = $mt->{cfg}->ObjectDriver =~ /^DBI::(.*)$/
        or die "No DBI ObjectDriver defined in mt.cfg";

    for my $class (@CLASSES) {
        print "Dumping $class\n";
        MT::Object->set_driver('DBI::' . $type);
        eval "use $class";
        my $iter = $class->load_iter;

        MT::Object->set_driver('DBM');
	my $i = 0;
        while (my $o = $iter->()) {
	    $i++;
            $o->save or die $o->errstr;
            print ".";
	    $i % 10 or print " ";
	    $i % 100 or print "\n";
        }
        print "\n\n";
    }
};

if ($@) {
    print <<HTML;
</pre>
<p><strong>An error occurred while loading data: $@</strong></p>
</body>
</html>
HTML
} else {
    print <<HTML;
</pre>
<p><strong>Done copying data from your SQL database to BerkeleyDB.</strong></p>
</body>
</html>
HTML
}
